package com.heny.demo.strategy.impl;

import com.heny.demo.entity.TurnPoint;
import com.heny.demo.strategy.FileParseStrategy;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author :wushen
 * @since :2025/5/11 16:44
 */

@Component("xlsx")
public class XlsxFileParseStrategy implements FileParseStrategy {

    private static final GeometryFactory geometryFactory = new GeometryFactory();

    @Override
    public List<TurnPoint> parseFile(MultipartFile file) throws IOException {
        List<TurnPoint> turnPoints = new ArrayList<>();
        try (InputStream inputStream = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(inputStream)) {

            Sheet sheet = workbook.getSheetAt(0);
            // 从第0行开始读取数据（移除标题行检查）
            for (int i = 0; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }

                TurnPoint turnPoint = new TurnPoint();
                turnPoint.setIndex(String.valueOf(row.getCell(0).getStringCellValue()));

                double x = getCellValue(row.getCell(1));
                double y = getCellValue(row.getCell(2));
                double z = getCellValue(row.getCell(3));

                Point point = geometryFactory.createPoint(new Coordinate(x, y));
                turnPoint.setCoordinate(point);

                turnPoints.add(turnPoint);
            }
        }
        return turnPoints;
    }

    private double getCellValue(Cell cell) {
        if (cell == null) {
            return 0;
        }
        switch (cell.getCellType()) {
            case NUMERIC:
                return cell.getNumericCellValue();
            case STRING:
                try {
                    return Double.parseDouble(cell.getStringCellValue());
                } catch (NumberFormatException e) {
                    return 0;
                }
            default:
                return 0;
        }
    }
}